package com.example.demo.es;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.po.Kimchy;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class GetConnection {
    public final static String HOST = "127.0.0.1";
    // http请求的端口是9200，客户端是9300
    public final static int PORT = 9300;
    private static final String RXPAY = "rxpay";
    private static final String ORDER = "order";
    private static TransportClient client;


    /**
     * getConnection:(获取es连接).
     *
     * @return
     * @throws Exception
     * @author xbq Date:2018年3月21日上午11:52:02
     */
    @SuppressWarnings({"resource", "unchecked"})
    public static TransportClient getConnection() throws Exception {
        // 设置集群名称
        Settings settings = Settings.builder()/*.put("cluster.name", "nmtx-cluster")*/.build();
        // 创建client
        client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));

        return client;
    }


    public static void main(String[] args) throws Exception {
        TransportClient client = getConnection();
        System.out.println("client==" + client.transportAddresses());
       /* JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderNo", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "001");
        jsonObject.put("orderName", "购买元宝");
        jsonObject.put("orderTime", new Date());
        jsonObject.put("price", 1.5);
        jsonObject.put("ip", "192.168.10.129");

        IndexResponse response =client.prepareIndex(RXPAY, ORDER).setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println("索引名称：" + response.getIndex());
        System.out.println("类型：" + response.getType());
        System.out.println("文档ID：" + response.getId()); // 第一次使用是1
        System.out.println("当前实例状态：" + response.status());*/
        //testQuery();
        //testUpdate();
        testSearch3();

    }


    /**
     * testQuery:(查询).
     *
     * @author xbq
     */
    @Test
    public void testQuery() {
        try {
            TransportClient client = getConnection();
            GetResponse response = client.prepareGet("rxpay", "order", "QYZUYmMBFaSBqFa3e5f1").execute().actionGet();
            System.out.println(response.getSourceAsString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * testUpdate:(更新).
     *
     * @author xbq
     */
    @Test
    public void testUpdate() {
        JSONObject json = new JSONObject();
        json.put("user", "Joe");
        json.put("age", "22");
        json.put("sex", "男");
        json.put("orderTime", "6666666");
        UpdateResponse response = client.prepareUpdate("rxpay", "order", "QYZUYmMBFaSBqFa3e5f1").setDoc(json.toJSONString(), XContentType.JSON).get();
        System.out.println("索引名称：" + response.getIndex());
        System.out.println("类型：" + response.getType());
        System.out.println("文档ID：" + response.getId());
        System.out.println("当前实例状态：" + response.status());
    }

    /**
     * testDelete:(删除).
     *
     * @author xbq
     */
    @Test
    public void testDelete() {
        DeleteResponse response = client.prepareDelete("rxpay", "order", "Q4ZZYmMBFaSBqFa3d5fs").get();
        System.out.println("索引名称：" + response.getIndex());
        System.out.println("类型：" + response.getType());
        System.out.println("文档ID：" + response.getId());
        System.out.println("当前实例状态：" + response.status());
    }

    @Test
    public static void testSearch() {
        SearchResponse searchResponse = client.prepareSearch("twitter")
                .setTypes("_doc")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.matchQuery("user", "kimchy"))
                .setFrom(0).setSize(20)
                .setExplain(true)// 设置是否按查询匹配度排序
                .get();
        SearchHits hits = searchResponse.getHits();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            System.out.println(hit.getSourceAsMap().toString());
        }
    }

    public static void testSearch2() {
        QueryBuilder termQueryBuilder = QueryBuilders.termQuery("user", "kimchy");
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("user");
        highlightBuilder.requireFieldMatch(false);
        SearchResponse searchResponse = client.prepareSearch("twitter")
                .setTypes("_doc")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(termQueryBuilder)
                .setFrom(0)
                .setSize(10)
                .setExplain(true)
                .highlighter(highlightBuilder)
                .get();
        SearchHits hits = searchResponse.getHits();
        hits.forEach(c -> {
            Map<String, HighlightField> highlightFields = c.getHighlightFields();
            HighlightField user = highlightFields.get("user");
            if (user != null) {
                StringBuilder stringBuilder = new StringBuilder();
                Text[] userFragments = user.getFragments();
                Arrays.stream(userFragments).forEach(r -> {
                    stringBuilder.append(r);
                });
                Map<String, Object> sourceAsMap = c.getSourceAsMap();
                sourceAsMap.put("highlight", stringBuilder.toString());
            }
            System.out.print(c.getScore());
            System.out.println(c.getSourceAsMap());
        });
        System.out.println("-----");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("user", "kimchy"));
        boolQueryBuilder.filter(QueryBuilders.matchQuery("message2", "hehe"));
        boolQueryBuilder.filter(QueryBuilders.termQuery("sta", 6));
        SearchResponse searchResponse2 = client.prepareSearch("twitter")
                .setTypes("_doc")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(boolQueryBuilder)
                .get();
        searchResponse2.getHits().forEach(c -> {
            Map<String, Object> sourceAsMap = c.getSourceAsMap();
            System.out.println(sourceAsMap);
            System.out.println("==");
            System.out.println(c.getSourceAsString());
            Kimchy kimchy = JSON.parseObject(c.getSourceAsString(), Kimchy.class);
            System.out.println(kimchy);
        });
        SearchHits hits1 = searchResponse2.getHits();
        System.out.println(hits1.getTotalHits());
        System.out.println(searchResponse2.getTook());

    }

    public static void testSearch3() {

        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("content", "呵呵");
        SearchRequestBuilder ikindex = client.prepareSearch("ikindex");
        SearchRequestBuilder test1 = ikindex.setTypes("test1").setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(matchQueryBuilder);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("content");
        highlightBuilder.requireFieldMatch(false);
        SearchResponse searchResponse = test1.highlighter(highlightBuilder).setExplain(true).get();
        SearchHits hits = searchResponse.getHits();
        hits.forEach(c -> {
            Map<String, Object> sourceAsMap = c.getSourceAsMap();
            Map<String, HighlightField> highlightFields = c.getHighlightFields();
            Map<String, Object> content = getHighlight(sourceAsMap, highlightFields, "content");
            System.out.println(content);
        });
    }
    public static Map<String, Object> getHighlight(Map<String, Object> sourceAsMap,Map<String, HighlightField> highlightFields, String fild) {
        System.out.println("测试测试branch");
        HighlightField highlightField = highlightFields.get(fild);
        if(highlightField!=null){
            StringBuilder stringBuilder = new StringBuilder();
            Text[] fragments = highlightField.getFragments();
            Arrays.stream(fragments).forEach(r -> {
                stringBuilder.append(r);
            });
            sourceAsMap.put("hilight",stringBuilder.toString());
            return sourceAsMap;
        }else{
            System.out.println("测试测试branch");
            return sourceAsMap;
        }
    }

}
